<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false" top="10px">
    <el-form :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="新闻标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="新闻标题"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="abstracts">
        <el-input v-model="dataForm.abstracts" placeholder="摘要" type="textarea"></el-input>
        <!-- <template #default="{ row }">
          <div class="ma_text" :title="row.abstracts">
            {{ row.abstracts }}
          </div>
        </template> -->
      </el-form-item>
      <!-- <el-form-item label="新闻地址">
        <el-button v-if="newsUpload === null ? true : !newsUpload.newsUrl" placeholder="新闻地址" type="primary"
          @click="newsUploadShow()">上传新闻地址</el-button>
        <el-input v-else disables :value="newsUpload.newsUrl"></el-input>
      </el-form-item> -->
      <el-form-item label="新闻封面" prop="ossCoverPhotoUrl">
        <!-- <el-button v-if="imgUrl !== null" type="primary" @click="imgShow(imgUrl)">查看原先的封面</el-button> -->
        <el-upload class="avatar-uploader"  :action="url" :file-list="fileList"  
          :before-upload="beforeUploadHandle" :on-success="successHandle">
          <img v-if="imgUrl" :src="imgUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="新闻内容" prop="ossBody" style="height: 420px;">
        <WangEditor v-model="dataForm.ossBody"></WangEditor>
      </el-form-item>
      <el-form-item label="访问量" prop="visits">
        <el-input v-model="dataForm.visits" placeholder="访问量"></el-input>
      </el-form-item>
      <el-form-item label="发布时间" prop="pubDate">
        <el-date-picker type="datetime" placeholder="新闻发布日期" v-model="dataForm.pubDate" format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"></el-date-picker>
      </el-form-item>
      <!-- <el-form-item label="状态" prop="status">
        <el-input v-model="dataForm.status" placeholder="状态"></el-input>
      </el-form-item> -->
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
  <!-- <news-upload ref="newsUpload"></news-upload> -->
  <el-dialog v-model="imgVisible" width="30%" top="10px">
    <img :src="imgUrl" style="width: 100%;height: 100%;">
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/cache";
import { IObject } from "@/types/interface";
import app from "@/constants/app"
// import NewsUpload from "@/views/poap/news-upload.vue";
import WangEditor from "@/components/wang-editor/index.vue";

const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

// const newsUpload = ref();
// const newsUploadShow = () => {
//   newsUpload.value.init();
// };

//图片上传逻辑
const url = ref(`${app.api}/oss/file/upload?access_token=${getToken()}`);
const num = ref(0);
const fileList = ref<IObject[]>();
const imgUrl = ref("");

const imgVisible = ref(false);

const imgShow = (row: any) => {
  imgVisible.value = true;
  imgUrl.value = row.ossCoverPhotoUrl
}

const visible = ref(false);
const dataFormRef = ref();

const dataForm = reactive({
  id: "",
  title: "",
  abstracts: "",
  ossCoverPhotoId: "",
  ossCoverPhotoUrl: "",
  ossBody: "",
  ossBodyId: "",
  visits: "",
  dictValue:"",
  pubDate: "",
  status: "",
  delFlag: "",
  createDate: "",
  creator: "",
  updateDate: "",
  updater: ""
});

const rules = ref({});

const init = (id?: number) => {
  visible.value = true;
  dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

// 获取信息
const getInfo = (id: number) => {
  baseService.get("/poapweb/poapnews/" + id).then((res) => {
    Object.assign(dataForm, res.data);
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if (!(dataForm.id || imgUrl.value !== '')) {
      ElMessage.error({
        message: "请上传新闻封面",
        duration: 500
      });
      return false;
    }
    // dataForm.ossCoverPhotoUrl = imgUrl.value;

    (!dataForm.id ? baseService.post : baseService.put)("/poapweb/poapnews", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};



// 上传之前
const beforeUploadHandle = (file: IObject) => {
  
  if (file.type !== "image/jpg" && file.type !== "image/jpeg" && file.type !== "image/png" && file.type !== "image/gif") {
    ElMessage.error(t("upload.tip", { format: "jpg、png、gif" }));
    return false;
  }
  num.value++;
};

// 上传成功
const successHandle = (res: IObject, file: IObject, list: IObject[]) => {
  imgUrl.value = URL.createObjectURL(list[0].raw);
  dataForm.ossCoverPhotoUrl = res.data.url;

  if (res.code !== 0) {
    return ElMessage.error(res.msg);
  }

  fileList.value = list;
  num.value--;
  if (num.value === 0) {
    ElMessage.success({
      message: t("prompt.success"),
      duration: 500,
      onClose: () => {
        // visible.value = false;
        emit("refreshDataList");
      }
    });
  }
};

defineExpose({
  init
});
</script>
<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

// .ma_text {
//   height: 10em;
//   overflow: hidden;
//   display: -webkit-box;
//   -webkit-line-clamp: 6;
//   -webkit-box-orient: vertical;
//   text-overflow: ellipsis;
//   white-space: normal;
//   position: relative;
// }
</style>
